#!/usr/bin/env swift

// 分析UUID二维码问题
// 根据用户截图，桌号显示为：Table50fcbcf0-5e0b-4be1-abcc-0203ab55cb35
// 这说明二维码内容包含UUID，但解析逻辑有问题

import Foundation

// 复制当前的QRScannerConfig解析逻辑
struct QRScannerConfig {
    struct URLParsing {
        static let expectedDomain = "azmobileapp.azurewebsites.net"
        static let expectedPathPrefix = "/Mr_bull/tabs/home"
        
        struct ParameterMapping {
            static let locationIdParam = "locationId"
            static let methodParam = "method"
            static let queryParam = "q"
            static let tokenParam = "t"
        }
        
        struct TableNumberGeneration {
            static let useLocationIdPrefix = false
            static let extractFromURLPath = true
            static let pathTableNumberPattern = "(?:table|t)?(\\d+)"
            static let extractFromQueryParam = true
            static let tableNumberQueryParams = ["table", "t", "tableNumber", "tableId", "id", "num"]
            static let locationIdPrefixLength = 4
            static let tablePrefix = "Table"
            static let convertHexToDecimal = true
            static let generateTwoDigitNumber = false
            static let twoDigitMinValue = 10
            static let twoDigitMaxValue = 99
            static let fallbackTableNumber = "未知桌号"
        }
    }
    
    static func parseTableNumber(from qrCodeContent: String) -> String {
        print("\n🔍 [解析调试] 开始解析: \(qrCodeContent)")
        
        // 尝试解析为URL
        guard let url = URL(string: qrCodeContent) else {
            print("❌ [解析调试] 无效URL格式，尝试从原始内容提取数字")
            // 尝试从原始内容中提取数字
            let numberPattern = "(\\d+)"
            if let regex = try? NSRegularExpression(pattern: numberPattern, options: []),
               let match = regex.firstMatch(in: qrCodeContent, options: [], range: NSRange(location: 0, length: qrCodeContent.count)),
               match.numberOfRanges > 1 {
                let range = match.range(at: 1)
                if let swiftRange = Range(range, in: qrCodeContent) {
                    let extractedNumber = String(qrCodeContent[swiftRange])
                    let result = URLParsing.TableNumberGeneration.tablePrefix + extractedNumber
                    print("✅ [解析调试] 从原始内容提取到桌号: \(result)")
                    return result
                }
            }
            print("❌ [解析调试] 原始内容中未找到数字，返回默认值")
            return URLParsing.TableNumberGeneration.fallbackTableNumber
        }
        
        // 检查URL是否符合预期格式
        let isValidDomain = url.host == URLParsing.expectedDomain
        let isValidPath = url.path.hasPrefix(URLParsing.expectedPathPrefix)
        
        print("🔍 [解析调试] URL分析:")
        print("   - Host: \(url.host ?? "无") (期望: \(URLParsing.expectedDomain)) \(isValidDomain ? "✅" : "❌")")
        print("   - Path: \(url.path) (期望前缀: \(URLParsing.expectedPathPrefix)) \(isValidPath ? "✅" : "❌")")
        print("   - Query: \(url.query ?? "无")")
        
        // 解析URL参数
        guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
            print("❌ [解析调试] 无法解析URL组件，尝试从原始内容提取数字")
            let numberPattern = "(\\d+)"
            if let regex = try? NSRegularExpression(pattern: numberPattern, options: []),
               let match = regex.firstMatch(in: qrCodeContent, options: [], range: NSRange(location: 0, length: qrCodeContent.count)),
               match.numberOfRanges > 1 {
                let range = match.range(at: 1)
                if let swiftRange = Range(range, in: qrCodeContent) {
                    let extractedNumber = String(qrCodeContent[swiftRange])
                    let result = URLParsing.TableNumberGeneration.tablePrefix + extractedNumber
                    print("✅ [解析调试] 从原始内容提取到桌号: \(result)")
                    return result
                }
            }
            print("❌ [解析调试] 原始内容中未找到数字，返回默认值")
            return URLParsing.TableNumberGeneration.fallbackTableNumber
        }
        
        let queryItems = components.queryItems ?? []
        let parameters: [String: String] = Dictionary(uniqueKeysWithValues: queryItems.compactMap { item in
            guard let value = item.value else { return nil }
            return (item.name, value)
        })
        
        // 优先级1：从查询参数中提取桌号
        if URLParsing.TableNumberGeneration.extractFromQueryParam {
            print("🔍 [解析调试] 尝试从查询参数提取桌号")
            print("   - 可用参数: \(parameters.keys.joined(separator: ", "))")
            
            for paramName in URLParsing.TableNumberGeneration.tableNumberQueryParams {
                if let tableNumber = parameters[paramName] {
                    let result = URLParsing.TableNumberGeneration.tablePrefix + tableNumber
                    print("✅ [解析调试] 从查询参数'\(paramName)'提取到桌号: \(result)")
                    return result
                }
            }
            print("❌ [解析调试] 未在查询参数中找到桌号")
        }
        
        // 其他解析逻辑...
        print("❌ [解析调试] 所有方法都未找到桌号，返回默认值")
        return URLParsing.TableNumberGeneration.fallbackTableNumber
    }
}

print("🔍 UUID二维码问题分析")
print(String(repeating: "=", count: 60))

// 根据截图分析可能的二维码内容格式
let possibleQRContents = [
    // 可能性1：纯UUID
    "50fcbcf0-5e0b-4be1-abcc-0203ab55cb35",
    
    // 可能性2：带前缀的UUID
    "table:50fcbcf0-5e0b-4be1-abcc-0203ab55cb35",
    "tableId:50fcbcf0-5e0b-4be1-abcc-0203ab55cb35",
    
    // 可能性3：URL格式包含UUID
    "https://azmobileapp.azurewebsites.net/Mr_bull/tabs/home?tableId=50fcbcf0-5e0b-4be1-abcc-0203ab55cb35",
    "https://azmobileapp.azurewebsites.net/Mr_bull/tabs/home?locationId=50fcbcf0-5e0b-4be1-abcc-0203ab55cb35",
    
    // 可能性4：JSON格式
    "{\"tableId\":\"50fcbcf0-5e0b-4be1-abcc-0203ab55cb35\",\"tableNumber\":null}",
    
    // 可能性5：其他格式
    "Table 50fcbcf0-5e0b-4be1-abcc-0203ab55cb35"
]

print("\n📋 测试不同的二维码内容格式:")
for (index, content) in possibleQRContents.enumerated() {
    print("\n测试 \(index + 1): \(content.prefix(50))...")
    let result = QRScannerConfig.parseTableNumber(from: content)
    print("结果: \(result)")
    
    // 检查是否会产生类似截图的问题
    if result.contains("50fcbcf0") {
        print("⚠️ 这种格式会导致截图中的问题！")
    }
}

print("\n" + String(repeating: "=", count: 60))
print("🎯 问题分析总结:")
print("")
print("根据截图显示的 'Table50fcbcf0-5e0b-4be1-abcc-0203ab55cb35'，")
print("问题很可能是以下几种情况之一：")
print("")
print("1. 🔍 二维码内容分析:")
print("   - 二维码可能包含完整的UUID字符串")
print("   - 当前解析逻辑错误地将UUID当作桌号处理")
print("   - 需要确认实际的二维码内容格式")
print("")
print("2. 🛠️ 可能的解决方案:")
print("   方案A: UUID映射 - 通过API将UUID转换为真实桌号")
print("   方案B: 二维码重新生成 - 直接在二维码中包含桌号")
print("   方案C: 解析逻辑修改 - 识别UUID格式并特殊处理")
print("")
print("3. 📝 需要的信息:")
print("   - 实际二维码的完整内容")
print("   - 后台数据库中UUID与桌号的映射关系")
print("   - 是否有API可以查询UUID对应的桌号")
print("")
print("4. 🚨 当前问题:")
print("   - 显示长UUID字符串影响用户体验")
print("   - 厨房单可能也显示UUID而非桌号")
print("   - 需要确定是前端解析问题还是后台数据问题")

print("\n💡 建议下一步:")
print("请提供一个实际二维码的完整内容，这样我可以：")
print("1. 准确分析二维码的数据格式")
print("2. 设计针对性的解析逻辑")
print("3. 实现UUID到桌号的正确映射")